<template>
  <div class="login-container">
    <!-- 注册表单模块 -->
    <div class="login-box">
      <h1>智能铁路售票系统</h1>
      <h2>用户注册</h2>
      <el-form 
        :model="registerForm" 
        :rules="rules" 
        ref="formRef"
        label-width="0" 
        class="login-form"
      >
        <!-- 姓名 -->
        <el-form-item prop="name">
          <el-input v-model="registerForm.name" placeholder="姓名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item prop="phone">
          <el-input v-model="registerForm.phone" placeholder="手机号">
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 账号 -->
        <el-form-item prop="username">
          <el-input v-model="registerForm.account" placeholder="账号">
            <template #prefix>
              <el-icon><Document /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="密码" show-password>
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item prop="confirmPassword">
          <el-input v-model="confirmPassword" type="password" placeholder="确认密码" show-password>
            <template #prefix>
              <el-icon><Check /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 身份证号 -->
        <el-form-item prop="idCard">
          <el-input v-model="registerForm.idNumber" placeholder="身份证号">
            <template #prefix>
              <el-icon></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 头像选择 -->
        <el-form-item  prop="avatarType">
          <el-select v-model="avatarType" placeholder="请选择头像类型" style="width: 100%">
            <el-option label="默认头像" value="default" />
            <el-option label="上传头像" value="upload" />
          </el-select>
        </el-form-item>

        <!-- 头像上传 -->
        <el-form-item v-if="avatarType === 'upload'" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="registerForm.avatar" :src="registerForm.avatar" class="avatar">
            <el-icon v-else><Plus/></el-icon>
          </el-upload>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm" class="login-btn">注册</el-button>
        </el-form-item>
        
        <el-form-item>
          <el-button @click="backToLogin" class="register-btn">返回登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { User, Lock, Plus,Check,Document,Phone } from '@element-plus/icons-vue'
import { defineComponent } from 'vue'
import { type RegisterDTO } from '../models/general'
import  { registerRequest }  from '../request/generalRequest'
import router from '../router/index'

export default defineComponent({
  components: {
    User,
    Lock,
    Plus,
    Check,
    Document,
    Phone
  },
  
  data: () => ({
  
    registerForm: {
      avatar: 'public/avatar/DefaultAvatar.jpg',
    } as RegisterDTO,
    confirmPassword: '',
    avatarType:'default',
    uploadAction: '/api/upload/avatar',
    rules: {
      account:[
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 15, message: '长度在3到15个字符', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 3, max: 15, message: '长度在3到15个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
      ],
      idNumber: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '身份证号格式不正确', trigger: 'blur' }
      ],
      avatarType: [
        { required: true, message: '请选择头像类型', trigger: 'blur' }
      ]

      
    }
  }),

  created() {
    // 初始化页面数据
  },

  methods: {
   // 头像上传成功回调
    handleAvatarSuccess(response: any, file: File) {
      if (response.code === 1) {
        this.registerForm.avatar = response.data // 将OSS地址保存到表单
      } else {
        alert('头像上传失败: ' + response.message)
      }
    },

    // 上传前校验
    beforeAvatarUpload(file: File) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isImage) {
        alert('只能上传图片文件!')
      }
      if (!isLt2M) {
        alert('头像图片大小不能超过2MB!')
      }
      
      return isImage && isLt2M
    },



    // 注册逻辑
    async submitForm() {
      if (this.registerForm.password !== this.confirmPassword) {
        alert('两次输入的密码不一致')
        return;
      }

    
  if (!this.registerForm.name) {
    alert('请设置姓名');
    return;
  }
  if (!this.registerForm.password) {
    alert('请设置密码');
    return;
  }
  if (!this.registerForm.phone) {
    alert('请设置电话');
    return;
  } if (!this.registerForm.idNumber) {
    alert('请填写身份证号码');
    return;
  } if (!this.registerForm.account) {
    alert('请填写账号');
    return;
  }

      try {
        const result = await registerRequest('/api/user/register', this.registerForm)
        console.log(result)
        
        if (result.code === 1) {
          alert('注册成功！')
          router.push({ path: '/' })
        } else {
          alert(`注册失败：${result.msg}`)
        }
      } catch (error) {
        console.error('注册请求失败:', error)
        alert('注册请求失败，请重试')
      }
    },

    // 跳转到登录页
    goLogin() {
      router.push({ path: '/' })
    }
  }
})

</script>

<style scoped>
.login-container {
  background: url('public/login_and_register/background_login.jpg') no-repeat center center fixed;
  background-size: cover;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 50px;
}

.login-box {
  background-color: rgba(255, 255, 255, 0.8);
  padding: 30px;
  border-radius: 8px;
  width: 380px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
}

.login-form :deep(.el-form-item__content) {
  width: 100%;
}

.login-btn, .register-btn {
  width: 100%;
}

.login-form :deep(.el-input__prefix) {
  display: flex;
  align-items: center;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100px;
  height: 100px;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409EFF;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>